<template>
  <div id="after-select">
    <!-- 带模板选题-无章节页面 -->
    <div class="jx-content add-time">
      <el-form
        class=""
        :inline="true"
        ref="searchForm"
        :model="searchForm"
        label-width="80px"
      >
        <el-form-item label="试卷名称 :">
          <el-input v-model="reqData.paperName" class="input-long"></el-input>
        </el-form-item>
        <!-- <el-form-item label="结束方式 :">
          <el-radio v-model="radioEnd" label="1">时长</el-radio>
          <el-radio v-model="radioEnd" label="2">日期</el-radio>
        </el-form-item>
        <el-form-item label="考试时间 :">
          <el-input
            @keyup.native="provingEx(reqData, 'timeLength')"
            v-model="reqData.timeLength"
          ></el-input>
        </el-form-item>
        <el-form-item label="分钟" class="form-left"></el-form-item> -->
        <el-form-item class="fr">
          <el-button @click.native="setParamsData" class="button-style">
            预 览
          </el-button>
          <el-button @click="submitData" class="button-style">保存试卷</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="jx-content is-modal">
      <div class="clearfix chose-model">
        <!-- <div class="title c-blue fs18 fbold fl">模板模式</div> -->
        <div class="fr">
          <el-tooltip
            class="item"
            effect="dark"
            content="按照模板定义规则生成试卷"
            placement="bottom"
          >
            <i style="vertical-align: -1px" class="iconfont icon-wenti-m c-blue fs18"></i>
          </el-tooltip>
        </div>
        <div class="fr c-blue fs16 table-button">
          <router-link
            :to="{
              path: '/Teaching/MyCourses/Examination/TestPaper/selectTemplate',
              query: { paperName: reqData.paperName, timeLength: reqData.timeLength },
            }"
          >
            <i class="iconfont icon-moban"></i>选择试题模板
          </router-link>
        </div>
      </div>
    </div>
    <div class="jx-content is-modal-bottom">
      <!-- 预览弹出框 -->
      <el-dialog
        :close-on-click-modal="false"
        width="850"
        class="dialog-questions"
        title="试题预览"
        :visible.sync="dialogQuestion"
      >
        <div class="dialog-content markdown-body">
          <div class="question-title" v-html="rowData.content"></div>
          <div
            v-if="rowData.questionType === 1"
            v-for="(item, index) in rowData.answer"
            :key="index"
            class="question-chose"
          >
            <span>{{ answerChose[index] }}：</span>
            <span class="question-flex" v-html="item.content"></span>
          </div>
          <div class="question-answer">
            答案：
            <span
              v-if="rowData.questionType === 3"
              class="chose"
              style="font-family: '黑体'; font-size: 16px"
              v-html="answerTrue"
            ></span>
            <span v-else class="chose" v-html="answerTrue"></span>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button class="button-style" @click="dialogQuestion = false"
            >确 定</el-button
          >
        </span>
      </el-dialog>
      <div class="search-box">
        <el-form
          class="fl"
          :inline="true"
          ref="searchForm"
          :model="searchForm"
          label-width="80px"
        >
          <el-form-item label="章节名称 :">
            <el-select
              :clearable="true"
              v-model="chapterId"
              placeholder="请选择"
              @change="selectChange"
            >
              <el-option
                v-for="(item, index) in chapterList"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="fr" style="margin-top: 5px; font-weight: bold">
          已选择 {{ nowCountSum }}题 总分数：{{ scoreSum }}分
        </div>
      </div>
      <div class="clear"></div>
      <div class="table-box">
        <div class="no-table-top"></div>
        <div class="tab-group" v-if="modeInfoChapterQuestionList">
          <!-- 题目类型 modeInfoChapterQuestionList -->
          <el-badge
            :hidden="!getQuestionTypeSum(item.type)"
            v-for="(item, index) in modeInfoChapterQuestionList"
            :key="index"
            :value="getQuestionTypeSum(item.type)"
            class="item"
          >
            <el-button
              :class="{ active: btnIndex == index }"
              @click="tabClick(item.type, index)"
            >
              {{ item.typeMessage }}
            </el-button>
          </el-badge>
          <div class="one-question-score" v-if="questionListItem">
            每题分数：
            <el-input
              @focus="focusScore($event)"
              @keyup.native="proving(questionListItem, 'score')"
              v-model="questionListItem.score"
            ></el-input>
            分
          </div>
        </div>
        <el-table
          @select-all="selectAll"
          @select="selectItem"
          ref="md"
          :data="modelListItem"
          style="width: 100%"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="content" label="试题题目">
            <template slot-scope="scope">
              <div
                :title="delHTMLLabel(scope.row.content)"
                style="text-align: left"
                class="question-content-timu beyond-hiding"
                v-html="delHTMLLabel(scope.row.content)"
              ></div>
            </template>
          </el-table-column>
          <el-table-column prop="chapterName" label="章节" width="180">
            <template slot-scope="scope">
              <div
                class="question-content-timu beyond-hiding"
                :title="scope.row.chapterName"
                v-html="scope.row.chapterName"
              ></div>
            </template>
          </el-table-column>
          <el-table-column label="分数" width="180">
            <template slot-scope="scope">{{ questionListItem.score }}</template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="200">
            <template slot-scope="scope">
              <div class="table-button">
                <el-button @click="dialogQuestionShow(scope.row)" type="text" size="small"
                  >预览</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import $ from "jquery";
export default {
  data() {
    return {
      //结束方式
      radioEnd: "1",
      //展示
      //章节列表包含题目类型
      chapterList: [],
      //arr
      //遍历题目类型
      //通过tab点击事件查找modelList中对应题型题目
      modelListItem: [],
      questionList: [],
      //obj 指定题型数组，里面的questionIdList用于存放指定题型id
      questionListItem: null,
      modeInfoChapterQuestionList: [],
      //已选择题数
      nowCountSum: 0,
      //试卷总分数
      score: 0,

      //获取暂存
      //列表数组
      modelList: [],
      //当前按钮index
      btnIndex: 0,

      //预览数据
      rowData: [],
      //试题正确答案
      answerTrue: "",
      //试题答案选项
      answerChose: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"],
      //预览弹出框
      dialogQuestion: false,
      //查看框显示
      lookContent: false,
      chapterId: "",
      reqData: {
        //模板id
        modelId: "",
        //试卷名称
        paperName: this.$route.query.paperName,
        //考试时间
        timeLength: this.$route.query.timeLength,
        //题目列表
        questionList: [
          {
            type: 1,
            typeMessage: "选择题",
            score: 1,
            questionIdList: [],
          },
          {
            type: 2,
            typeMessage: "判断题",
            score: 1,
            questionIdList: [],
          },
          {
            type: 3,
            typeMessage: "填空题",
            score: 1,
            questionIdList: [],
          },
          {
            type: 4,
            typeMessage: "简答题",
            score: 1,
            questionIdList: [],
          },
          {
            type: 5,
            typeMessage: "编程题",
            score: 1,
            questionIdList: [],
          },
          {
            type: 6,
            typeMessage: "实验题",
            score: 1,
            questionIdList: [],
          },
        ],
      },
      searchForm: {
        chapterName: "",
        chapterId: "",
      },
    };
  },
  created() {
    let paperName = this.$route.query.paperName;
    console.log(paperName, 333);
  },
  computed: {
    //计算总分
    scoreSum() {
      let that = this;
      let questionList = that.questionList;
      if (questionList.length) {
        let result = questionList
          .map((item) => item.score * item.questionIdList.length)
          .reduce((total, num) => total + num);
        return result;
      }
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    //获取模板信息 -》 获取章节信息 -> 按模板过滤章节
    //切换章节 -> 获取该章节题目列表
    //列表加载后再执行操作
    init() {
      this.getTopicSelected();
      this.getList();
      this.lookQuestion();
      this.questionList = this.reqData.questionList;
    },
    //文字全选
    focusScore(event) {
      event.currentTarget.select();
    },
    delHTMLLabel(str) {
      let reg = /<[^>]*>|<\/[^>]*>/gm;
      let result = str.replace(reg, "");
      return result;
    },
    //验证**************************************************************************************
    //输入验证 键盘抬起事件 限制input框只能输入正整数
    provingEx(item, prop) {
      let that = this;
      //限制输入数字
      console.log(item[prop], 55);
      let reg = /^[0-9]+$/;
      let isInt = reg.test(item[prop]);
      console.log(isInt, 66);
      if (!isInt) {
        item[prop] = "";
        console.log(item[prop], 77);
        that.$message.warning("只能输入数字");
      }
      //限制不能大于120
      let isQuesNum = item[prop] > 120 || item[prop] < 1;
      if (isQuesNum) {
        item[prop] = "";
        that.$message.warning("考试时间为1-120分钟");
      }
    }, //输入验证 键盘抬起事件 限制input框只能输入正整数
    proving(item, prop) {
      let that = this;
      //限制输入数字
      console.log(item[prop], 55);
      let reg = /^[0-9]+$/;
      let isInt = reg.test(item[prop]);
      console.log(isInt, 66);
      if (!isInt) {
        item[prop] = 1;
        console.log(item[prop], 77);
        that.$message.warning("只能输入数字");
      }
      if (item[prop] > 100) {
        item[prop] = 1;
        that.$message({
          type: "warning",
          message: "分数不能大于100",
        });
      }
    },
    //提交验证 预览和保存试卷 整合reqData发送数据+验证
    //整合reqData发送数据
    filterReqData() {
      let that = this;
      let reqData = that.reqData;
      //总分
      reqData.score = that.scoreSum;

      //验证
      if (!reqData.paperName) {
        that.$message.warning("请填写考试名称");
        return;
      }

      if (reqData.paperName.length > 20) {
        that.$message.warning("考试名称不能超过20字");
        return;
      }

    //   if (!reqData.timeLength) {
    //     that.$message.warning("请填写考试时间");
    //     return;
    //   }

      if (!that.nowCountSum) {
        that.$message.warning("请选择题目");
        return;
      }

      if (!that.scoreSum) {
        that.$message.warning("请添加分数");
        return;
      }

      return true;
    },

    //**************************************************************************************** */

    //获取题目类型和章节下拉
    getTopicSelected() {
      var that = this;
      axios
        .get(
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/businessType/1/question-repository/dropdown-list"
        )
        .then(function (res) {
          console.log("成功");
          console.log(res);
          if (res.status === 200) {
            if (res.data.code === 200) {
              //赋值章节列表
              let chapterList = res.data.data.chapterList;
              that.chapterList = chapterList;
            }
          }
        })
        .catch(function (err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    },

    //切换章节 获取章节题目列表
    selectChange(val) {
      this.getList(val);
    },
    //获取所有题型题目列表modelList
    getList(chapterId) {
      let that = this;
      axios
        .get(
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/businessType/1/question-repository/question-by-type",
          { params: { chapterId: that.chapterId } }
        )
        .then(function (res) {
          console.log("成功");
          console.log(res);
          if (res.status === 200) {
            if (res.data.code === 200) {
              let modelList = res.data.data;
              console.log(res.data.data, 3333);
              that.modelList = modelList;
              if (modelList.length === 0) {
                that.modelListItem = [];
              }
              //填空题替换(+)为（）
              $.each(modelList, function (i, d) {
                if (d.type == 3) {
                  $.each(d.questionList, function (i2, d2) {
                    let str = d2.content;
                    var result = str.replace(/\(\+\)/g, "（）"); //把(+)替换成()
                    d2.content = result;
                  });
                }
              });
              console.log(that.modelList, 1);
              //设置当前章节题型
              that.setModelBtns(chapterId);
            } else {
              that.$message({
                message: res.data.message,
                type: "error",
              });
            }
          }
        })
        .catch(function (err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    //设置章节中题型 遍历tab头 ,设置之后默认选中第一个 在列表获取后执行
    setModelBtns(chapterId) {
      let that = this;
      let modelList = that.modelList;
      //按照已有题型加载tab头
      let modeInfoChapterQuestionList = modelList.map((item) => {
        let obj = {
          type: item.type,
          typeMessage: item.typeMessage,
        };
        return obj;
      });
      that.modeInfoChapterQuestionList = modeInfoChapterQuestionList;
      //获取数据后默认点击第一个tab，需在数据加载完成后点击
      let questionType = that.modeInfoChapterQuestionList[0].type;
      that.tabClick(questionType, 0);
    },

    //tab头的点击事件 点击查找modelList列表中当前题型所有题目，并赋值给modelListItem
    //切换题型
    tabClick(type, index) {
      let that = this;
      //高亮
      that.btnIndex = index;
      //tab头点击，查找并改变table列表展示数据
      that.setModeListItem(type);
      //更新题型存放id数组
      that.setQuestionListItem(type);
      //回填
      that.upDataChecked();
    },
    //tab头点击，查找并改变table列表展示数据
    setModeListItem(type) {
      let that = this;
      let modelList = that.modelList;
      that.modelListItem = modelList.find((item) => item.type === type).questionList;
      console.log(that.modelListItem, 55);
    },
    //设置当前存储id盒子
    setQuestionListItem(type) {
      let that = this;
      that.questionListItem = that.reqData.questionList.find(
        (item) => item.type === type
      );
    },
    //回填，切换tab回填已选择数据，通过modelInfoItem中的已储存questionIdList，在当前列表中modelListItem找到对应行回填
    upDataChecked() {
      let that = this;
      let modelListItem = that.modelListItem;
      let questionIdList = that.questionListItem.questionIdList;
      console.log(modelListItem);
      modelListItem.forEach((item) => {
        let isChecked = questionIdList.some((item2) => item.id === item2);
        if (isChecked) {
          that.$nextTick(function () {
            that.$refs.md.toggleRowSelection(item, true);
          });
        }
      });
    },

    //表格单选
    selectItem(rows, row) {
      let that = this;
      //选中存储到指定的questionIdList中
      that.saveIdList(rows, row);
    },
    //全选
    selectAll(rows) {
      let that = this;
      let questionIdList = that.questionListItem.questionIdList;
      //是否选中
      let selected = rows.length;
      if (selected) {
        //选中 添加到指定题型中
        questionIdList.push(...rows.map((item) => item.id));
        //去重
        that.questionListItem.questionIdList = Array.from(new Set(questionIdList));
        //已选择题数
        that.nowCountSum += rows.length;
      } else {
        //?????
        console.log(66666);
        let rowsId = that.$refs.md.data.map((item) => item.id);
        that.questionListItem.questionIdList = questionIdList.filter((item) =>
          rowsId.every((item2) => item2 !== item)
        );
        that.nowCountSum -= rowsId.length;
      }
      console.log(questionIdList);
    },
    //选中存储到指定的questionIdList中
    saveIdList(rows, row) {
      let that = this;
      let questionIdList = that.questionListItem.questionIdList;
      //是否选中
      let selected = rows.length && rows.indexOf(row) !== -1;
      if (selected) {
        //选中 添加到指定题型中
        questionIdList.push(row.id);
        //已选择题数
        that.nowCountSum++;
      } else {
        //取消选中 从指定题型中删除
        questionIdList.splice(
          questionIdList.findIndex((item) => item == row.id),
          1
        );
        //已选择题数
        that.nowCountSum--;
      }
    },
    //计算各类型已选题数
    getQuestionTypeSum(type) {
      let that = this;
      let obj = that.questionList.find((item) => item.type === type);
      if (obj) {
        return obj.questionIdList.length;
      }
    },
    //预览试卷
    setParamsData() {
      let that = this;
      if (!that.filterReqData()) {
        return;
      }
      //本地存储
      let storage = window.localStorage;
      //storage.removeItem('previewPaperData');
      console.log(that.reqData, 445566);
      let reqData = JSON.stringify(that.reqData);
      storage.setItem("previewPaperData", reqData);
      //新窗口打开
      let routerData = that.$router.resolve({
        path: `/PreviewTestPaper/`,
      });
      window.open(routerData.href, "_blank");
    },

    //预览试题
    dialogQuestionShow(row) {
      this.dialogQuestion = true;
      console.log(row, 4);
      this.rowData = row;
      //添加答案
      let answer = row.answer;
      this.answerTrue = "";
      let answerTrue = "";
      //选择题
      if (row.questionType === 1) {
        //遍历找出正确答案选项
        for (let x in answer) {
          console.log(answer[x].isCorrect, 4456);
          if (answer[x].isCorrect) {
            console.log(answer[x].isCorrect);
            answerTrue += this.answerChose[x];
          }
        }
        this.answerTrue = answerTrue;
      }
      //判断题
      if (row.questionType === 2) {
        if (answer[0].isCorrect) {
          this.answerTrue = "正确";
        } else {
          this.answerTrue = "错误";
        }
      }
      //填空题,简答，实验
      if (row.questionType === 3 || row.questionType === 4 || row.questionType === 6) {
        this.answerTrue = answer[0].content;
      }
    },

    //查看模板
    lookQuestion() {
      let that = this;
      $(".look-question-btn")
        .mouseenter(function () {
          that.lookContent = true;
        })
        .mouseleave(function () {
          that.lookContent = false;
        });
    },
    //保存试卷
    submitData() {
      let that = this;
      if (!that.filterReqData()) {
        return;
      }
      const loading = that.$loading({
        lock: true,
        text: "正在保存中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      axios
        .post(
        //   `/tes/course/927/course-test/paper/no-preview`
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/course-test/paper/no-preview",
          that.reqData
        )
        .then(function (res) {
          loading.close();
          console.log("成功");
          console.log(res);
          if (res.status === 200) {
            if (res.data.code === 200) {
              let modelList = res.data.data;
              that.$message({
                message: "添加成功",
                type: "success",
              });
              that.$router.push({ path: "ExaminationList" });
            } else {
              that.$message({
                message: res.data.message,
                type: "error",
              });
            }
          }
        })
        .catch(function (err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "../../../styles/img-init";
</style>

<style lang="scss">
@import "../../../styles/layout/color_variables";
#after-select {
  .form-left label {
    text-align: left;
  }
  .input-long .el-input__inner {
    width: 200px;
  }
  img {
    max-width: 80%;
  }
  width: 1200px;
  margin: 0px auto 30px;
  .el-badge sup {
    right: 12px;
  }
  .tab-group {
    margin-bottom: 20px;
    position: relative;
    button {
      border: 1px solid #d9d9d9;
      padding: 0 20px;
      height: 40px;
      line-height: 40px;
      color: #474747;
      margin-left: -1px;
      border-radius: 0;
    }
    .active {
      background: #1277eb;
      color: #fff;
    }
  }
  .table-box thead .el-checkbox {
    // display: none;
  }
  .add-time {
    .el-form-item {
      margin-bottom: 0;
    }
    .button-style {
      margin-left: 10px;
    }
  }
  .is-modal {
    margin-bottom: -60px;
  }
  .is-modal-bottom {
    box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
  }
  .btn-group {
    font-size: 0;
    margin: 0 0 20px 1px;
    .btn-tab {
      display: inline-block;
      font-size: 14px;
      height: 38px;
      line-height: 38px;
      border: 1px solid #d9d9d9;
      padding: 0 20px;
      margin-left: -1px;
    }
    .btn-tab:hover,
    .btn-tab.active {
      background: $btn-blue;
      border-color: $btn-blue;
      color: #fff;
      cursor: pointer;
    }
    .el-badge__content.is-fixed {
      z-index: 9;
    }
  }
  .el-badge__content {
    right: -10px;
    z-index: 1;
  }
  .el-tabs__nav-scroll {
    overflow: initial;
    &:after {
      content: "";
      display: block;
      clear: both;
    }
  }
  .el-tabs__nav-wrap {
    overflow: initial;
  }
  .el-badge:first-child .btn-tab {
    border-top-left-radius: 6px;
    border-bottom-left-radius: 6px;
  }
  .el-badge:last-child .btn-tab {
    border-top-right-radius: 6px;
    border-bottom-right-radius: 6px;
  }

  .el-tabs__nav-wrap::after {
    background: none;
  }
  .el-tabs__nav {
    margin-left: 1px;
  }
  .el-tabs__item {
    border: 1px solid #d9d9d9;
    padding: 0 20px;
    height: 40px;
    line-height: 40px;
    color: #474747;
    margin-left: -1px;
  }
  .el-tabs__item.is-active {
    background: #1277eb;
    color: #fff;
  }
  .el-tabs__active-bar {
    background: none;
  }
  #tab-first {
    border-top-left-radius: 6px;
    border-bottom-left-radius: 6px;
  }
  #tab-fifth {
    position: relative;
    border-top-right-radius: 6px;
    border-bottom-right-radius: 6px;
  }
  .dialog-questions {
    .el-dialog__body {
      max-height: 500px;
      overflow: auto;
    }
    .dialog-content {
      padding: 20px 64px 0;
      .question-title {
        font-weight: bold;
        font-size: 16px;
        margin-bottom: 20px;
        p {
          line-height: 30px;
        }
      }
      .question-chose {
        font-size: 14px;
        line-height: 24px;
        padding: 6px 0;
        display: flex;
        .question-flex {
          flex: 1;
          p {
            line-height: 24px;
          }
        }
      }
      .question-answer {
        font-size: 16px;
        .chose {
          font-size: 18px;
          color: #385899;
          vertical-align: -2px;
          p {
            line-height: 30px;
          }
        }
        margin-top: 20px;
      }
    }
    .el-dialog__footer {
      text-align: center;
    }
  }
  .chose-model {
    margin-bottom: 10px;
  }
  .iconfont {
    margin: 0 5px;
  }
  .look-question {
    position: relative;
    display: inline-block;
    cursor: pointer;
    .look-question-content {
      cursor: auto;
      position: absolute;
      z-index: 10;
      color: #727272;
      left: 10px;
      top: 36px;
      padding: 20px 34px;
      box-sizing: border-box;
      background: #fff;
      border: 1px solid #e8e8e8;
      .look-question-item {
        display: flex;
        justify-content: space-between;
        line-height: 32px;
        border-bottom: 1px solid #e8e8e8;
        padding: 0 6px;
        font-size: 14px;
        .chapter-name {
          min-width: 100px;
        }
        .look-question-item2 {
          width: 100%;
          display: flex;
          justify-content: space-between;
          > div {
            min-width: 70px;
            text-align: center;
          }
        }
      }
      .look-question-score {
        font-size: 14px;
      }
    }
  }
  .del-modal {
    cursor: pointer;
  }
  .el-tabs__content {
    overflow: initial;
  }
  .one-question-score {
    position: absolute;
    top: 0;
    right: 0;
    .el-input {
      width: 150px;
    }
  }
}
</style>
